"use client"

import type React from "react"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Loader2 } from "lucide-react"

export default function StoryGenerator() {
  const [formData, setFormData] = useState({
    character: "",
    location: "",
    background: "",
    plotType: "",
  })
  const [story, setStory] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError("")
    setStory("")

    try {
      const response = await fetch("/api/generate-story", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || "生成故事失败")
      }

      setStory(data.story)
    } catch (err) {
      setError(err instanceof Error ? err.message : "发生未知错误")
    } finally {
      setLoading(false)
    }
  }

  const handleInputChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 p-4">
      <div className="max-w-4xl mx-auto">
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-gray-900 mb-2">儿童睡前故事生成器</h1>
          <p className="text-gray-600">输入故事元素，为孩子生成专属的睡前故事</p>
        </div>

        <div className="grid md:grid-cols-2 gap-6">
          <Card>
            <CardHeader>
              <CardTitle>故事元素</CardTitle>
              <CardDescription>请填写以下信息来生成个性化故事</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <Label htmlFor="character">主要人物</Label>
                  <Input
                    id="character"
                    placeholder="例如：小兔子、勇敢的小女孩"
                    value={formData.character}
                    onChange={(e) => handleInputChange("character", e.target.value)}
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="location">故事地点</Label>
                  <Input
                    id="location"
                    placeholder="例如：魔法森林、海底世界"
                    value={formData.location}
                    onChange={(e) => handleInputChange("location", e.target.value)}
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="background">故事背景</Label>
                  <Input
                    id="background"
                    placeholder="例如：寻找宝藏、帮助朋友"
                    value={formData.background}
                    onChange={(e) => handleInputChange("background", e.target.value)}
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="plotType">情节类型</Label>
                  <Input
                    id="plotType"
                    placeholder="例如：冒险、友谊、成长"
                    value={formData.plotType}
                    onChange={(e) => handleInputChange("plotType", e.target.value)}
                    required
                  />
                </div>

                <Button type="submit" className="w-full" disabled={loading}>
                  {loading ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      正在生成故事...
                    </>
                  ) : (
                    "生成故事"
                  )}
                </Button>
              </form>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>生成的故事</CardTitle>
              <CardDescription>您的专属儿童睡前故事</CardDescription>
            </CardHeader>
            <CardContent>
              {error && (
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded mb-4">{error}</div>
              )}

              {story ? (
                <Textarea
                  value={story}
                  readOnly
                  className="min-h-[400px] resize-none"
                  placeholder="故事将在这里显示..."
                />
              ) : (
                <div className="min-h-[400px] flex items-center justify-center text-gray-500 border-2 border-dashed border-gray-200 rounded">
                  {loading ? "正在生成您的专属故事..." : "填写故事元素后点击生成故事"}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
